import format from 'date-fns/format'

import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { Textarea } from '@/components/ui/textarea'
import useRequest from '@/utils/request'
import { useDispatch, useSelector } from 'react-redux'
import { selectCurMention, setMentions } from '@/store/mention-slice'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect, useState } from 'react'
import { useToast } from '@/components/ui/use-toast'
import { Sparkles, Send, ExternalLink } from 'lucide-react'
import { setConfig } from '@/store/config-slice'
import { selectCurProject } from '@/store/project-slice'
import { selectPaginationConfig, fetchPaginatedData } from '@/store/mention-slice'

const FormSchema = z.object({
  reply: z
    .string()
    .min(3, {
      message: 'Please enter a reasonable keyword (between 3 and 50 characters).',
    })
    .max(1000, {
      message: 'Please enter a reasonable keyword (between 3 and 50 characters).',
    }),
})

export function MailDisplay({ mail }) {
  const request = useRequest()
  const curMention = useSelector(selectCurMention)
  const curProject = useSelector(selectCurProject)
  const [filled, setFilled] = useState(false)
  const dispatch = useDispatch()
  const { toast } = useToast()
  const paginationConfig = useSelector(selectPaginationConfig)

  const form = useForm({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      reply: '',
    },
  })

  const watchAllFields = form.watch()

  useEffect(() => {
    const subscription = form.watch((value, { name, type }) => {
      setFilled(value.reply.trim() === '' ? false : true)
    })
    return () => subscription.unsubscribe()
  }, [watchAllFields])

  async function onSubmit(data) {
    try {
      await request.put('red_growth/mention', { ...data, id: curMention.selected })
      toast({
        title: `Your reply has been ready to publish.`,
        description: 'It usually take up within 3 - 12 hours to see the effect.',
      })

      form.reset()

      dispatch(
        fetchPaginatedData({
          project_id: curProject.id,
          replyType: paginationConfig.replyType,
          current: paginationConfig.currentPage,
          pageSize: paginationConfig.perPage,
        })
      )

      const configRes = await request.get('account/config')
      dispatch(setConfig(configRes.data))
    } catch (error) {
      console.error('Error submitting form:', error)
    }
  }

  const generateReply = async data => {
    const res = await request.delete(`red_growth/generate_reply?id=${curMention.selected}`)
    form.setValue('reply', res.data.reply)
  }

  return (
    <div className="flex h-full flex-col">
      {mail ? (
        <div className="flex flex-1 flex-col">
          <div className="flex items-start p-4">
            <div className="flex items-start gap-4 text-sm">
              <Avatar>
                <AvatarImage alt={mail.keyword} />
                <AvatarFallback>
                  {mail.keyword
                    .split(' ')
                    .map(chunk => chunk[0])
                    .join('')}
                </AvatarFallback>
              </Avatar>
              <div className="grid gap-1">
                <div className="font-semibold">{mail.keyword}</div>
                <div className="line-clamp-1 text-xs">r/{mail.sr}</div>
              </div>
            </div>
            {/* {mail.date && (
              <div className="ml-auto text-xs text-muted-foreground">{format(new Date(mail.createtime), 'PPpp')}</div>
            )} */}
            <div className="ml-auto text-xs text-muted-foreground">
              <div className="grid gap-2 grid-center">
                <a
                  className="flex justify-center items-center font-medium text-primary underline underline-offset-4"
                  href={mail.url}
                  target="_blank"
                >
                  <ExternalLink className="mr-1 text-2" size={16} />
                  View post
                </a>
                {mail.reddit_reply && mail.reddit_reply.response_url && (
                  <a
                    className="flex justify-center items-center font-medium text-primary underline underline-offset-4"
                    href={mail.reddit_reply.response_url}
                    target="_blank"
                  >
                    <ExternalLink className="mr-1 text-2" size={16} />
                    View reply
                  </a>
                )}
              </div>
            </div>
          </div>
          <Separator />

          <div className="flex-1 whitespace-pre-wrap p-4 text-sm">
            <div className="flex w-fit max-w-[85%] flex-col gap-2 rounded-lg px-4 py-2 text-sm bg-muted">
              {mail.content}
            </div>
            {mail.reddit_reply_id > 0 && (
              <>
                <div className="w-fit max-w-[85%] rounded-lg px-4 py-2 text-sm ml-auto bg-primary text-primary-foreground mt-4">
                  {/* Sounds good! Let&apos;s meet at the <span className="underline decoration-wavy">Starbucks</span> on 5th
                Ave. */}
                  {mail.reddit_reply.content}
                </div>
                <p className="flex justify-end px-2 pt-1 text-muted-foreground">
                  {parseInt(mail.reddit_reply.status) === 0 && 'ready to publish'}
                  {parseInt(mail.reddit_reply.status) === 1 && 'publish failed'}
                  {parseInt(mail.reddit_reply.status) === 2 && 'published'}
                </p>
              </>
            )}
          </div>

          <Separator className="mt-auto" />
          <div className="p-4">
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)}>
                <div className="grid gap-4">
                  <FormField
                    control={form.control}
                    name="reply"
                    render={({ field }) => (
                      <FormItem>
                        {/* <FormLabel>Keyword to monitor:</FormLabel> */}
                        <FormControl>
                          <Textarea className="p-4" placeholder={`Reply to it`} {...field} />
                        </FormControl>
                        {/* <FormDescription>
                        Enter only one keyword or phrase at a time. Any symbols or spaces will be matched literally.
                      </FormDescription> */}
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <div className="flex items-center">
                    {filled ? (
                      <Button disabled={mail.reddit_reply_id > 0} type="submit" size="sm" className="ml-auto">
                        <Send className="w-4 mr-1" />
                        Send
                      </Button>
                    ) : (
                      <Button
                        disabled={mail.reddit_reply_id > 0}
                        onClick={e => {
                          e.preventDefault()
                          generateReply()
                        }}
                        size="sm"
                        className="ml-auto"
                      >
                        <Sparkles className="w-4 mr-1" />
                        Generate reply
                      </Button>
                    )}
                  </div>
                </div>
              </form>
            </Form>
          </div>
        </div>
      ) : (
        <div className="p-8 text-center text-muted-foreground">No mention selected</div>
      )}
    </div>
  )
}
